import React, { useEffect } from "react";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import { useRouteMeta } from "@/hooks/useRouteMeta";
import { useSelector } from "react-redux";
import { message } from "antd";

const GlobalRouter: React.FC<React.PropsWithChildren> = () => {
  const meta: any = useRouteMeta();
  const { token } = useSelector((state: any) => state.user);
  const navigate = useNavigate();
  const location = useLocation();

  // 权限校验
  useEffect(() => {
    // 1. 需要登录但没登录，跳转到登录页
    if (meta.requiresAuth && !token) {
      navigate("/login", { replace: true });
    }
    // 2. 已登录还访问 login，跳转到首页
    if (location.pathname === "/login" && token) {
      navigate("/", { replace: true });
    }
  }, [meta.requiresAuth, token, navigate, location.pathname]);

  // 动态标题
  useEffect(() => {
    if (meta.title) {
      document.title = meta.title;
    }
  }, [meta.title]);

  return <Outlet />;
};

export default GlobalRouter;
